﻿using AutoMapper;
using IOA.MES.DataAccess.Entity;
using IOA.MES.DataAccess.Enum;
using IOA.MES.DataAccess.VModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IOA.MES.Common;
using System.Threading.Tasks;

namespace IOA.MES.Business
{
    /// <summary>
    /// 设备管理（错误代码：119001）
    /// </summary>
    public class MachineMgr
    {
        private MESContext mesDb = new MESContext("MES");

        /// <summary>
        /// 获取设备对象
        /// </summary>
        /// <param name="machineId">设备ID</param>
        /// <returns>设备对象</returns>
        public VMachine GetMachine(int machineId, string machineNo = "")
        {
            var entity = machineId > 0 ? mesDb.Machines.AsNoTracking().FirstOrDefault(_ => _.PkId == machineId && _.Valid)
                : mesDb.Machines.AsNoTracking().FirstOrDefault(_ => _.MachineNo == machineNo && _.Valid);
            var model = Mapper.Map<VMachine>(entity);
            model.LineName = mesDb.AssemblyLines.AsNoTracking().FirstOrDefault(_ => _.PkId == entity.LineId)?.LineName;
            return model;
        }

        /// <summary>
        /// 编辑设备
        /// </summary>
        /// <param name="model">设备对象</param>
        public void EditMachine(VMachine model)
        {
            var workshop = mesDb.Workshops.AsNoTracking().FirstOrDefault(_ => _.WorkshopCode == model.WorkshopCode && _.Valid);
            if (workshop == null)
            {
                throw new MultiLanBizException(119001);// "车间不存在");
            }
            var line = model.LineId <= 0 ? null : mesDb.AssemblyLines.AsNoTracking().FirstOrDefault(_ => _.PkId == model.LineId && _.Valid);
            model.WorkshopName = workshop.WorkshopName;
            model.LineName = line?.LineName;
            if (model.PkId <= 0)
            {
                var exist = mesDb.Machines.FirstOrDefault(_ => _.WorkshopCode == model.WorkshopCode && _.LineId == model.LineId && _.MachineName == model.MachineName && _.Valid);
                if (exist != null)
                {
                    throw new MultiLanBizException(119002);// "设备名称已存在，请更换其他名称");
                }
                model.Status = CommonStatus.Normal;
                model.CreateTime = DateTime.Now;
                model.ModifyBy = 0;
                var entity = Mapper.Map<Machine>(model);
                mesDb.Machines.Add(entity);
            }
            else
            {
                var exist = mesDb.Machines.FirstOrDefault(_ => _.WorkshopCode == model.WorkshopCode && _.LineId == model.LineId && _.MachineName == model.MachineName && _.PkId != model.PkId && _.Valid);
                if (exist != null)
                {
                    throw new MultiLanBizException(119002);// "设备名称已存在，请更换其他名称");
                }
                var entity = mesDb.Machines.FirstOrDefault(_ => _.PkId == model.PkId && _.Valid);
                if (entity == null)
                {
                    throw new MultiLanBizException(119003);// "设备不存在或已被删除，无法编辑");
                }
                entity.MachineNo = model.MachineNo;
                entity.MachineName = model.MachineName;
                entity.IpHost = model.IpHost;
                entity.Manufacturers = model.Manufacturers;
                entity.MachineModel = model.MachineModel;
                entity.WorkshopCode = model.WorkshopCode;
                entity.WorkshopName = model.WorkshopName;
                entity.LineId = model.LineId;
                entity.LineName = model.LineName;
                entity.MachineIndex = model.MachineIndex;
                entity.ModifyBy = model.ModifyBy;
                entity.ModifyTime = DateTime.Now;
            }
            mesDb.SaveChanges();
        }

        /// <summary>
        /// 查询设备对象
        /// </summary>
        /// <param name="workshopCode">车间代码</param>
        /// <param name="machineType">设备类型</param>
        /// <param name="machineIndex">车间内序号</param>
        /// <returns></returns>
        public VMachine GetMachine(string workshopCode, MachineType machineType, int machineIndex)
        {
            var entity = mesDb.Machines.AsNoTracking().FirstOrDefault(_ => _.WorkshopCode == workshopCode && _.MachineType == machineType
                && _.MachineIndex == machineIndex && _.Valid);
            return Mapper.Map<VMachine>(entity);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ipHost"></param>
        /// <returns></returns>
        public VMachine GetMachineByIp(string ipHost)
        {
            var entity = mesDb.Machines.AsNoTracking().FirstOrDefault(_ => _.IpHost == ipHost && _.Valid);
            return Mapper.Map<VMachine>(entity);
        }

        /// <summary>
        /// 查询设备列表
        /// </summary>
        /// <param name="pageIndex">页面索引</param>
        /// <param name="pageSize">页面容量</param>
        /// <param name="total">总数</param>
        /// <param name="workshopCode">车间ID</param>
        /// <param name="lineId">流水线ID</param>
        /// <param name="status">状态</param>
        /// <param name="machineType">设备类型</param>
        /// <returns>设备列表</returns>
        public List<VMachine> QueryMachines(int pageIndex, int pageSize, out int total, string workshopCode, int lineId, CommonStatus? status, MachineType? machineType = null)
        {
            var query = mesDb.Machines.Where(_ => _.Valid);
            if (status.HasValue)
            {
                query = query.Where(_ => _.Status == status.Value);
            }
            if (!string.IsNullOrWhiteSpace(workshopCode))
            {
                query = query.Where(_ => _.WorkshopCode == workshopCode);
            }
            if (lineId > 0)
            {
                query = query.Where(_ => _.LineId == lineId);
            }
            if (machineType.HasValue)
            {
                query = query.Where(_ => _.MachineType == machineType.Value);
            }
            total = query.Count();
            query = query.OrderBy(_ => _.WorkshopCode).ThenBy(_ => _.LineId).ThenBy(_ => _.MachineType).ThenBy(_ => _.MachineName);

            var entities = pageSize <= 0 ? query.ToList() : query.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            var models = Mapper.Map<List<VMachine>>(entities);
            var lineIds = models.Where(_ => _.LineId > 0).Select(_ => _.LineId).Distinct().ToList();
            var lines = mesDb.AssemblyLines.Where(_ => lineIds.Contains(_.PkId) && _.Valid).ToList();
            models.ForEach(machine =>
            {
                machine.LineName = lines.FirstOrDefault(_ => _.PkId == machine.LineId)?.LineName;
            });
            return models;
        }

        /// <summary>
        /// 查询车间设备列表
        /// </summary>
        /// <param name="workshopCode">车间ID</param>
        /// <param name="machineType">设备类型</param>
        /// <returns>设备列表</returns>
        public List<VMachine> QueryWorkshopMachines(string workshopCode, MachineType? machineType = null)
        {
            var query = mesDb.Machines.AsNoTracking().Where(_ => _.Valid);
            if (!string.IsNullOrWhiteSpace(workshopCode))
            {
                query = query.Where(_ => _.WorkshopCode == workshopCode);
            }
            if (machineType.HasValue)
            {
                query = query.Where(_ => _.MachineType == machineType.Value);
            }
            var entities = query.ToList();

            return Mapper.Map<List<VMachine>>(entities);
        }

        /// <summary>
        /// 修改设备状态
        /// </summary>
        /// <param name="model">设备对象</param>
        public void ModifyStatus(VMachine model)
        {
            var exist = mesDb.Machines.FirstOrDefault(_ => _.PkId == model.PkId && _.Valid);
            if (exist == null)
            {
                throw new MultiLanBizException(119004);// "设备不存在，无法修改状态");
            }
            exist.Status = model.Status;
            exist.ModifyBy = model.ModifyBy;
            exist.ModifyTime = DateTime.Now;
            mesDb.SaveChanges();
        }

        /// <summary>
        /// 查询设备类型列表
        /// </summary>
        /// <returns>设备类型列表</returns>
        public List<KeyValuePair<MachineType, string>> QueryMachineTypes()
        {
            var types = new List<KeyValuePair<MachineType, string>>();
            foreach (int code in Enum.GetValues(typeof(MachineType)))
            {
                types.Add(new KeyValuePair<MachineType, string>((MachineType)code, EnumConvert.ToDesc((MachineType)code)));
            }
            return types;
        }

        /// <summary>
        /// 提交层压机配置
        /// </summary>
        public void SaveTopMachineSetting(VTopMachineSetting model)
        {
            var machine = mesDb.Machines.AsNoTracking().FirstOrDefault(_ => _.PkId == model.MachineId && _.Valid);
            if (machine == null)
            {
                throw new MultiLanBizException(119003);// "设备不存在或已被删除，无法编辑");
            }

            var exist = mesDb.TopMachineSettings.Where(_ => _.MachineId == model.MachineId && _.Layer == model.Layer && _.Cavity == model.Cavity && _.Valid)
                .OrderByDescending(_ => _.PkId).FirstOrDefault();
            if (exist != null &&
                string.Equals((exist.InflationTime ?? 0).ToString("0.00"), (model.InflationTime ?? 0).ToString("0.00")) &&
                string.Equals((exist.Pressure1 ?? 0).ToString("0.00"), (model.Pressure1 ?? 0).ToString("0.00")) &&
                string.Equals((exist.Pressure2 ?? 0).ToString("0.00"), (model.Pressure2 ?? 0).ToString("0.00")) &&
                string.Equals((exist.Pressure3 ?? 0).ToString("0.00"), (model.Pressure3 ?? 0).ToString("0.00")) &&
                string.Equals((exist.PressureDelayTime1 ?? 0).ToString("0.00"), (model.PressureDelayTime1 ?? 0).ToString("0.00")) &&
                string.Equals((exist.PressureDelayTime2 ?? 0).ToString("0.00"), (model.PressureDelayTime2 ?? 0).ToString("0.00")) &&
                string.Equals((exist.Temp ?? 0).ToString("0.00"), (model.Temp ?? 0).ToString("0.00")) &&
                string.Equals((exist.TopTime ?? 0).ToString("0.00"), (model.TopTime ?? 0).ToString("0.00")) &&
                string.Equals((exist.UpperVacuumDelayTime ?? 0).ToString("0.00"), (model.UpperVacuumDelayTime ?? 0).ToString("0.00")) &&
                string.Equals((exist.VacuumPumpingTime ?? 0).ToString("0.00"), (model.VacuumPumpingTime ?? 0).ToString("0.00")))
            {
                return;
            }

            var entity = Mapper.Map<TopMachineSetting>(model);
            entity.WorkShopCode = machine.WorkshopCode;
            entity.WorkShopName = machine.WorkshopName;
            entity.MachineNo = machine.MachineNo;
            entity.CreateTime = DateTime.Now;
            mesDb.TopMachineSettings.Add(entity);
            mesDb.SaveChanges();
        }
    }
}
